package netty.rpc.framework.core.netty.loadbalance.impl;

import lombok.extern.slf4j.Slf4j;
import netty.rpc.framework.core.netty.loadbalance.LoadBalance;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author guiyiqiao
 * @date 2020/12/5
 *
 * 使用随机数形式进行负载均衡
 */
@Slf4j
public class RandomLoadBalance implements LoadBalance {
    /**
     * ThreadLocalRandom 保证多线程下随机数生成的安全性
     */

    ThreadLocalRandom random = ThreadLocalRandom.current();

    @Override
    public String selectServiceAddress(List<String> serviceList) {
        if(serviceList == null || serviceList.size() == 0){
            log.error("负载均衡时不存在可用服务地址！");
            return null;
        }
        int index = random.nextInt(serviceList.size());
        return serviceList.get(index);
    }
}
